//
//  KAEncrypt.swift
//  kano
//
//  Created by Sophia on 2024/8/15.
//

import Foundation
import CryptoSwift
import UIKit

class KAEncrypt {

    static let AES_KEY = "qwcf974a5261c3ce836167733803fb18"
    
    static func dealAESKey(key: String) -> String {
        let md5Str = key.md5()
        return String(md5Str.prefix(16))
    }
    
    static func stringToHexStr(_ str: String) -> String {
        guard !str.isEmpty else { return "" }
        let data = str.data(using: .utf8)!
        return data.map { String(format: "%02x", $0) }.joined()
    }
    
    static func hexStrToString(_ str: String) -> String {
        guard !str.isEmpty else { return "" }
        var hexData = Data()
        var index = str.startIndex
        
        while index < str.endIndex {
            let nextIndex = str.index(index, offsetBy: 2)
            let hexCharStr = String(str[index..<nextIndex])
            guard let byte = UInt8(hexCharStr, radix: 16) else { return "" }
            hexData.append(byte)
            index = nextIndex
        }
        return String(data: hexData, encoding: .utf8) ?? ""
    }
    
    // Encrypt information
    static func ka_encrypt(_ info: String) -> String {
        guard let baseZuid = UIDevice.ka_UUID.data(using: .utf8)?.base64EncodedString() else {
            return ""
        }
        let aesKey = AES_KEY + baseZuid
        let finalKey = dealAESKey(key: aesKey)
        do {
//            let aes = try AES(key: finalKey, iv: "", padding: .pkcs7)
            let aes = try AES(key: finalKey.bytes, blockMode: ECB(), padding: .pkcs7)
            let ciphertext = try aes.encrypt(info.bytes)
            let resultString = ciphertext.toBase64()
            //print("Encrypted data: \(ciphertext.toBase64())")
            return stringToHexStr(resultString)
            
        } catch {
            print("Error: \(error)")
        }
        return ""
    }
    
    // Decrypt information
    static func ka_decrypt(_ encrypted: String) -> String {
        guard let baseZuid = UIDevice.ka_UUID.data(using: .utf8)?.base64EncodedString() else {
            return ""
        }
        let aesKey = AES_KEY + baseZuid
        let finalKey = dealAESKey(key: aesKey)
        
        let resultString = hexStrToString(encrypted)
        let ciphertext = Array(base64: resultString)
        do {
            let aes = try AES(key: finalKey.bytes, blockMode: ECB(), padding: .pkcs7)
            let decrypted = try aes.decrypt(ciphertext)
            let decryptedString = String(bytes: decrypted, encoding: .utf8)
            print("Decrypted string: \(decryptedString!)")
            return decryptedString!
        } catch {
            print("Error: \(error)")
        }
        return ""
    }

}


